package com.example.test.support;


import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.example.test.support.gmhelper.SM3Util;
import com.example.test.support.gmhelper.SM4Util;
import com.google.gson.Gson;

import java.lang.reflect.Type;

import okhttp3.MediaType;

/**
 * 乾堂接口工具方法类
 */
public final class QianToonApiUtil {
    private static final String TAG = "QianToonApiUtil";
    /*** 获取token的参数  大众端*/
    public static final String QIANTOON_APP_ID = "QTappPat2020";
    public static final String QIANTOON_APP_SECRET= "131CE0EEC996F317";

    /*** 获取token的参数  医护端端*/
    public static final String QTDOCTOR_APP_ID = "QTappDoc2020";
    public static final String QTDOCTOR_APP_SECRET= "03C1F92FCB8F494A";

    /*** 头部默认参数KEY */
    public static String HEAD_KEY = "A13H212J1FSDWWE";
    public static String SM_APPID = "adminAppID";
    private static MediaType defaultMediaType;

    /**
     * 加密
     */
    public static String sm4Encrypt(String timeStamp, String data) {
        return SM4Util.getSm4EncryptECB(data, createSecretKey(timeStamp));
    }

    /**
     * 生成秘钥
     */
    private static String createSecretKey(String timeStamp) {
        return SM3Util.GetSm3Str(SM_APPID + timeStamp);
    }


    /**
     * 解密
     */
    @Nullable
    public static String sm4Decrypt(String timeStamp, String data) {
        return SM4Util.getSm4DecryptECB(data, createSecretKey(timeStamp));
    }

    /**
     * 解密
     */
    @Nullable
    public static <T> T sm4Decrypt(String timeStamp, String data, Class<T> clazz) {
        if (TextUtils.isEmpty(data))
            return null;
        try {
            return new Gson().fromJson(SM4Util.getSm4DecryptECB(data, createSecretKey(timeStamp)), clazz);
        } catch (Exception e) {
            LogUtils.eTag(TAG, "sm4Decrypt: 数据格式错误");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     */
    @Nullable
    public static <T> T sm4DecryptByType(String timeStamp, String data, Type type) {
        if (TextUtils.isEmpty(data))
            return null;
        try {
            return new Gson().fromJson(SM4Util.getSm4DecryptECB(data, createSecretKey(timeStamp)), type);
        } catch (Exception e) {
            LogUtils.eTag(TAG, "sm4DecryptByType: 数据格式错误");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前时间戳
     */
    public static String getTimeStamp() {
        return Long.toString(System.currentTimeMillis());
    }

    public static MediaType getDefaultMediaType() {
        if (defaultMediaType == null) {
            defaultMediaType = MediaType.parse("application/json; charset=utf-8");
        }
        return defaultMediaType;
    }
}
